package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void insert(String keyword,Integer useId) {
        log.info("准备存入manggodb{}",keyword);
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(useId);
        apUserSearch.setKeyword(keyword);

        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(useId).and("isDelete").is(0));
        ApUserSearch apUserSearchInMongDB = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearchInMongDB == null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }else {
            apUserSearchInMongDB.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearchInMongDB);
        }

    }

    @Override
    public ResponseResult findUserSearch() {
        Query query = Query.query(Criteria.where("userId").is(ThreadLocalUtil.get()).and("isDelete").is(0));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        Query id = Query.query(Criteria.where("id").is(dto.getId()));
        ApUserSearch one = mongoTemplate.findOne(id, ApUserSearch.class);
        one.setIsDelete(1);
        mongoTemplate.save(one);
        return ResponseResult.okResult("成功删除");
    }
}
